<template>
    <view v-if="showPopup" class="content" @click.stop.prevent="onTouchBg"> 
      <view v-if="isAutoMode">
        <view class="auto-popup">
          <view class="auto-popup-title">正在下载视频</view>
          <progress class="auto-popup-progress" stroke-width="8" :percent="totalPercent" show-info activeColor="#10AEFF" backgroundColor="#F6F7F8"/>
        </view>
      </view>
      
      <view v-else class="list-popup" style="width: 70%; height: 50%;">
        <view class="titlebar">
          <text class="title">视频下载</text>
          <view class="btn-close" @click="close">
            <text class="text-close" >{{'\ue723'}}</text>
          </view>
        </view>
        <view class="list-title">
          <view class="list-title-text col-name">视频名</view>
          <!-- <view class="list-title-text col-keyword">关键字</view> -->
          <view class="list-title-text col-size">大小</view>
          <view class="list-title-text col-state">状态</view>
          <view class="list-title-text col-btns" style="text-align: center;">操作</view>
        </view>
        <scroll-view class="list-wrap" :scroll-y="true" :show-scrollbar="false">
          <view class="list-item" v-for="(item, index) in dataList" :key="item.name">
            <view class="item-text-name col-name">
              <text class="item-text">{{item.name}}</text>
            </view>
            <!-- <text class="item-text col-keyword">{{item.keyword}}</text> -->
            <text class="item-text col-size">{{formatSize(item.total)}}</text>
            <text class="item-text col-state" :class="{'text-succ':isDownloaded(item)}" >{{stateDesc(item)}}</text>
            <view class="col-operation col-btns">
              <!-- 按钮:下载 -->
              <view class="btn-box">
                <text v-if="isDownloading(item)" class="btn-text" @click="onBtnStopDownload(item, index)">{{'\ue663'}}</text>
                <text v-if="canDownload(item)" class="btn-text" @click="onBtnStartDownload(item)">{{'\ue8c6'}}</text>
              </view>
              
              <!-- 按钮:打开目录 -->
              <view class="btn-box" @click="onBtnOpenDir">
                <text class="btn-text">{{'\ue602'}}</text>
              </view>
              
              <!-- 按钮:删除 -->
              <view class="btn-box">
                <text v-show="canDeleteTask(item)" class="btn-text" @click="onBtnDeleteVideo(item)">{{'\ue723'}}</text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
</template>

<script>
  const helper = require('../../static/js/helper.js') 
  const State = { None: 0, Downloading: 1, Downloaded: 2, Pause: 3, Fail: 4 } // 与 electron 目录下的 utils.js 内定义保持一致
  var localVideoList //本地视频文件列表:  [ {name:, size:, state:,} ]
  var serverVideoList //远程视频文件列表: [ {name:, size:, ulr:, }] 
  
  
  export default {
    data() {
      return {
        showPopup: false,
        isAutoMode: false,
        popStyle: '',
        listHeight: 400,
        dataList: [ 
          // {name: 'demo.mp4', url:'http://61.169.159.99:9695/test/demo.mp4', loaded:, total: 16039614, state: State.None },
        ],
        totalPercent: 0,
      }
    },
    mounted() {
      var self = this 
      console.log('=== mounted') 
      this.initView() 
    },
    destroyed() {
      window.api?.stopDownloadAll() 
    },
    computed: {
      formatSize() {
        return function(size) {
          if (size <= 0) {
            return "0";
          } else if (size < 1024) {
            return size + "B";
          } else if (size < 1024 * 1024) {
            return (size / 1024).toFixed(2) + "KB";
          } else if (size < 1024 * 1024 * 1024){
            return (size / 1024 / 1024).toFixed(2) + "MB";
          } else {
            return (size / 1024 / 1024 / 1024).toFixed(2) + "GB";
          }
        }
      }, 
      stateDesc() {
        return function(item) {
          let str = '待下载'
          if (item.state === State.Downloading || item.state === State.Pause) {
            str = parseInt(Math.min(100, 100*item.loaded/item.total)) + ' %'
          } else if (item.state === State.Downloaded) {
            str = '已下载'
          } else if (item.State === State.Fail) {
            str = '下载失败'
          } 
          return str 
        }
      },
      isDownloading() {
        return function(item) {
          return item.state === State.Downloading 
        }
      },
      isDownloaded() {
        return function(item) {
          return item.state === State.Downloaded 
        }
      },
      canDownload() {
        return function(item) {
          return item.state !== State.Downloaded && item.state !== State.Downloading 
        }
      },
      canDeleteTask() {
        return function(item) {
          return item.state === State.Downloading || item.state === State.Pause  
        }
      },
      isDownloadPaused() {
        return function(item) {
          return item.state === State.Pause
        }
      },
    },
    methods: {
      initView() {
        var self = this 
        // this.$nextTick(()=>{
        //   let query = uni.createSelectorQuery()
        //   query.select(".content").boundingClientRect()
        //   query.select(".titlebar").boundingClientRect()
        //   query.exec(res => {
        //     if (res) {
        //       if (res[0] && res[0].height > 0) {
        //         let winWidth    = res[0].width 
        //         let popScale    = parseInt(100*(winWidth > 640 ? 0.7 : 0.8));
        //         let popHeight   = Math.min(600, parseInt(res[0].height * popScale)) 
        //         self.popStyle   = `width:${popScale}%;height:${popHeight}px;`
        //         self.listHeight = parseInt(popHeight - res[1].height - 10)
        //         console.log('=== popScale, popHeight, listHeight: ', popScale, popHeight, self.listHeight)
        //       }
        //     }
        //   });
        // })
      },
      
      // 初始化用户当前已有的视频 
      initMyVideo: async function() { 
        let list = await helper.getVideolist() 
        serverVideoList   = list.map(it=>{
          let extName     = it.upload_url.substring(it.upload_url.lastIndexOf('.'))
          let nameWithExt = it.video_name.endsWith(extName) ? it.video_name : (it.video_name+extName) 
          return { name: it.video_name, nameWithExt, url: it.upload_url, size: it.file_size} 
        })
        
        localVideoList = await window.api?.getLocalVideoFiles(true)
        console.log('=== 本地视频列表: ', JSON.stringify(localVideoList))
        this.dataList = serverVideoList.map(it=>{
          let local   = localVideoList ? localVideoList.find(v=>v.name === it.nameWithExt) : null 
          let state   = local ? local.state : State.None 
          let loaded  = local ? local.size : 0 
          let total   = it.size 
          let item    = { name:it.name, url:it.url, loaded, total, state} 
          return item 
        }) 
        console.log('=== dataList: ', JSON.stringify(this.dataList)) 
      },
      onTouchBg(e) {
        e.stopPropagation();//取消冒泡
      },
      open() {
        console.log('=== open')
        this.showPopup  = true 
        this.isAutoMode = false 
        this.initMyVideo(()=>{}) 
      }, 
      close() { 
        this.showPopup  = false 
        this.isAutoMode = false 
      },
      
      // 后台自动下载, 如果有下载项则自动展示详情页面 
      autoDownload: function(finishCallback) {
        var self = this 
        console.log('[video_download] 开始检查视频下载...')
        
        this.initMyVideo().then( async ()=>{
          let list = self.dataList.filter(it=>{
            return it.loaded !== it.total || it.state !== State.Downloaded 
          })
          console.log('\n[video_download] 下载列表:', JSON.stringify(list))
          
          await window.api?.stopDownloadVideos()
          
          if (list.length > 0) {
            self.showPopup  = true 
            self.isAutoMode = true 
            window.api?.startDownloadVideos(list, (res)=>{
              if (res.state === 'progress') {
                self.totalPercent = Math.floor(Math.min(100, 100*res.loaded/res.total))
                
              } else if (res.state === 'success') {
                self.totalPercent = 100 
                uni.$emit('Evt_RefreshLocalVideo') 
                setTimeout(()=>{
                  self.close() 
                  if (finishCallback) finishCallback();
                }, 1000)
                
              } else if (res.state === 'error') {
                uni.showModal({
                  title: '提示',
                  content: '视频更新失败，请检查网路',
                  confirmText: '重试',
                  success(res) {
                    if (res.confirm) {
                      self.autoDownload() 
                    } else {
                      self.close()
                      if (finishCallback) finishCallback();
                    }
                  }
                })
              }
            }) 
          } else {
            if (finishCallback) finishCallback();
          }
          
        }) 
      },
      
      updateDownloadState(res) {
        // console.log('---- updateDownloadState: ', JSON.stringify(res))
        let item = this.dataList.find(it=>it.name===res.name)
        if (!item) return;
        
        if (res.state === 'progress') {
          item.state = State.Downloading 
          item.loaded = res.loaded 
          // console.log('---------------------- loaded:', item.loaded)
        } else if (res.state === 'success') {
          item.state = State.Downloaded 
          item.loaded = item.total 
          uni.$emit('Evt_RefreshLocalVideo') 
          
        } else if (res.state === 'error') {
          item.state = State.Fail 
        }
      },
      onBtnStartDownload: async function(item) {
        if (helper.isInBlock('key_download')) return;
        helper.setInBlock('key_download') 
        
        console.log('xxx onBtnStartDownload, state:', item.state, JSON.stringify(item)) 
        
        if (item.state === State.Downloaded) {
          var self = this 
          uni.showModal({
            title: '提示',
            content: '文件已下载，是否重新下载并覆盖原文件？',
            success: async function(res) {
              if (res.confirm) {
                let err = await window.api?.deleteVideo(item.name) 
                if (err) {
                  uni.showToast({title: '文件被占用，请手动删除后再重试', icon: 'none'})
                } else {
                  window.api?.startDownloadVideo({name: item.name, url: item.url, loaded: item.loaded, total: item.total}, self.updateDownloadState) 
                } 
              }
            }
          })
        } else {
          if (item.loaded > item.total) {
            console.log('### loaded, total:', item.loaded, item.total)
            uni.showModal({
              title: '提示',
              content: `本地文件与远程文件大小不一致: ${item.name}`,
              showCancel:false 
            })
          } else {
            console.log('### begin:', item.loaded)
            window.api?.startDownloadVideo({name: item.name, url: item.url, loaded: item.loaded, total: item.total}, this.updateDownloadState) 
          }
        }
      },
      onBtnStopDownload: async function(item) {
        if (helper.isInBlock('key_stopdownload')) return;
        helper.setInBlock('key_stopdownload') 
        if (item.state == State.Downloading) {
          await window.api?.stopDownloadVideo(item.name)
          console.log('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 停止下载:', item.name, item.loaded)
          setTimeout(()=>{
            item.state = State.Pause
          }, 100) 
        }
      },
      onBtnOpenDir() {
        window.api?.openVideoDir() 
      },
      onBtnDeleteVideo: function(item) {
        if (helper.isInBlock('key_delete')) return;
        helper.setInBlock('key_delete') 
        
        uni.showModal({
          title: '提示',
          content: '确定要删除下载任务？',
          success: async function(res) {
            if (res.confirm) {
              if (item.state === State.Downloading) {
                await window.api?.stopDownloadVideo(item.name) 
              }
              setTimeout( async ()=>{
                let err = await window.api?.deleteDownloadTask(item.name)
                if (err) {
                  uni.showModal({
                    title: '提示',
                    content: `删除文件“${item.name}”失败，请手动删除`,
                    showCancel:false
                  })
                } else {
                  item.loaded = 0 
                  item.state  = State.None 
                }
              }, 100) 
            }
          }
        }) 
      },
    }
  }
</script>


<style scoped>
@font-face {
  font-family: "iconfont";
  src: url('@/static/font/iconfont.ttf');
}
.content {
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  bottom: 0; 
  z-index: 100;
  
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.list-popup {
  width: 100%;
  height: 100%;
  border-radius: 6px;
  background-color: #4b4b4b;
  display: flex;
  flex-direction: column;
}
.titlebar {
  width: 100%;
  height: 36px;
  border-radius: 6px 6px 0 0;
  background-color: #666;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  position: relative;
}
.title {
  font-size: 14px;
  color: #fff;
}
.btn-close {
  height: 100%;
  padding: 0 10px;
  border-radius: 0 6px 0 0;
  position: absolute;
  right: 0;
  top: 0;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
.btn-close:hover {
  background-color: #565656;
}
.text-close {
  font-family: "iconfont";
  font-size: 16px;
  color: #cccccc;
}
.list-wrap {
  flex: 1;
  width: 100%;
  padding-bottom: 6px;
  box-sizing: border-box;
}
.list-title {
  width: 100%;
  height: 36px;
  padding: 0 10px;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  align-items: center;
  background-color: #333;
}
.list-title-text {
  font-size: 12px;
  font-weight: bold;
  color: #00a6f9;
}
.list-item {
  width: 100%;
  height: 46px;
  padding: 0 10px;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  align-items: center;
  border-bottom: 1px solid #6c6c6c;
}
.list-item:hover {
  background-color: #565656;
}
.item-text {
  font-size: 12px;
  color: #d5d5d5;
  box-sizing: border-box;
  
  display: -webkit-box; 
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1; 
  overflow: hidden;
  text-overflow: ellipsis; 
  word-break: break-all; 
}
.item-text-name {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.text-default {
  font-size: 12px;
  color: #00ff00;
  margin-left: 4px;
}
.text-succ {
  color: #00ff00;
}
.col-name {
  flex: 1;
  padding-right: 4px;
}
.col-keyword {
  width: 80px;
  padding-right: 4px;
  box-sizing: border-box;
  word-break: break-all;
  
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1; 
  overflow: hidden;
  text-overflow: ellipsis; 
}
.col-size {
  width: 160px;
}
.col-state {
  width: 120px;
}
.col-btns {
  width: 130px;
}
.col-operation {
  height: 100%;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: center;
}
.btn-box {
  width: 26px;
  height: 30px;
  margin-left: 10px;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
.btn-text {
  font-family: "iconfont";
  font-size: 16px;
  color: #d5d5d5;
}
.btn-text:hover {
  color: #fff;
}
.auto-popup {
  width: 500rpx;
  padding: 20rpx 30rpx;
  margin-top: 300rpx;
  border-radius: 8rpx;
  background-color: #4b4b4b;
  display: flex;
  flex-direction: column;
}
.auto-popup-title {
  font-size: 30rpx;
  color: #FFF;
}
.auto-popup-progress {
  width: 100%;
  height: 25px;
  margin-top: 8rpx;
}
/* 这主要是加上deep才能改变它原来的样式 */
/deep/ .uni-progress-bar {
  border-radius: 4px !important;
  overflow: hidden;

  /*其他修改样式, 比如修改背景色*/
  /* background-color: red !important; */
}
/deep/ .uni-progress-info {
  font-size: 12px;
  color: #FFF;
}



</style>
